package be.ipl.diavolo.servlets;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import be.ipl.Diavolo.exceptions.ArgumentInvalideException;
import be.ipl.Diavolo.exceptions.JoueurInexistantException;
import be.ipl.Diavolo.ucc.GestionJoueur;


/**
 * Servlet implementation class Connexion
 */
@WebServlet(name="connexion.html")
public class Connexion extends HttpServlet {
	private static final long serialVersionUID = 1L;
	@EJB
	private GestionJoueur gestionJoueur;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(request.getParameter("action") != null && request.getParameter("action").equals("deco")){
			request.getSession().removeAttribute("joueur");
		}
		response.sendRedirect(response.encodeRedirectURL("index.html"));
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String pseudo =  request.getParameter("pseudo");
		String mdp =  request.getParameter("mdp");
		
		try {
			gestionJoueur.connexion(pseudo, mdp);
		} catch (ArgumentInvalideException e) {
			e.printStackTrace();
		} catch (JoueurInexistantException e) {
			
			String message = "Erreur de connexion avec "+pseudo+" "+mdp;
			request.setAttribute("messErr", message);
			getServletContext().getNamedDispatcher("index.html").forward(request, response);
			
		}
		try {
			request.getSession().setAttribute("joueur", gestionJoueur.rechercherJoueur(pseudo));
		} catch (JoueurInexistantException e) {
			e.printStackTrace();
		} catch (ArgumentInvalideException e) {
			e.printStackTrace();
		}
		response.sendRedirect(response.encodeRedirectURL("connecte.html"));
		
	}

}